package pl.edu.mimuw.mas.test;

import jade.content.lang.Codec.CodecException;
import jade.content.onto.OntologyException;
import jade.content.onto.basic.Action;
import jade.domain.FIPANames;
import jade.lang.acl.ACLMessage;
import pl.edu.mimuw.mas.agent.ClientAgent;
import pl.edu.mimuw.mas.agent.behaviour.MutableTimedBehaviour;
import pl.edu.mimuw.mas.chart.Chart;
import pl.edu.mimuw.mas.ontology.VisualizationCoreOntology;
import pl.edu.mimuw.mas.ontology.concept.LogEntry;
import pl.edu.mimuw.mas.ontology.concept.Position;
import pl.edu.mimuw.mas.utils.Marshaller;

/**
 * Testowy agent poprosu łazi po planszy. 
 */
public class DummyClientAgent extends ClientAgent {
	private static final long serialVersionUID = -4874630536398749327L;

	private Chart chart;
	private int x, y;
	private int r, g, b;
	
	@SuppressWarnings("serial")
	protected void setup() {
		if(!setServiceAgents()) {
			doDelete();
			return;
		}
		
		setLanguages();
		
		// Wczytuje mape
		try {
			Object[] obj = getArguments();
			
			String fileName = (String) obj[0];
			chart = (Chart) Marshaller.read(fileName);
			
			if (chart == null) {
				doDelete();
				return;
			}
			
			x = (Integer) obj[1];
			r = (Integer) obj[2];
			g = (Integer) obj[3];
			b = (Integer) obj[4];
					
		} catch (ClassCastException e) {
			doDelete();
			return;
		} catch (NullPointerException e) {
			doDelete();
			return;
		}

		addBehaviour(new MutableTimedBehaviour(this, 700) {
			public void onTick() {
				try {
					// VIZ					
					
					ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);

					msg.addReceiver(getViz2DAgent());
					msg.addReceiver(getViz3DAgent());
					msg.setOntology(VisualizationCoreOntology.ONTOLOGY_NAME);
					msg.setLanguage(FIPANames.ContentLanguage.FIPA_SL);
					Position pos = new Position(myAgent.getName(), x, y, chart.getHeight(x, y), r, g, b);
					getContentManager().fillContent(msg, pos);
					y++;

					myAgent.send(msg);
					
					// LOG
					msg = new ACLMessage(ACLMessage.INFORM);

					msg.addReceiver(getLogAgent());
					msg.setOntology(VisualizationCoreOntology.ONTOLOGY_NAME);
					msg.setLanguage(FIPANames.ContentLanguage.FIPA_SL);
					Action a = new Action(getAID(), new LogEntry(getName(), "hello world: " + y));
					getContentManager().fillContent(msg, a);

					myAgent.send(msg);
				} catch (CodecException e) {
					e.printStackTrace();
				} catch (OntologyException e) {
					e.printStackTrace();
				}
			}
		});
	}
}
